<template>
  <div class="flex-column topo-link-segment">
    <div :class="['search-box', showRight ? 'active' : '']">
      <div class="flex justify-between" :class="['title', showRight ? 'active' : '']">
        <span><i class="iconfont icon-AFScengji" /> {{ $t('INTERMEDIATE_NODE') }}</span>
      </div>
      <div :class="['search', showRight ? 'active' : '']">
        <div class="flex">
          <el-input
            v-model.trim="queryData.keyword"
            style="width: 224px"
            class="mr-10"
            maxlength="32"
            clearable
            :placeholder="$t('LINK_SEGMENT_NAME') + '/' + $t('CABLE_NAME') + '/' + $t('NODE_NAME')"
            @keyup.enter.native="$debounce(search)"
          />
          <el-select
            v-model="stationType"
            clearable
            style="width: 224px"
            :placeholder="$t('SELECT_STATION')"
            @change="selectedIds = []"
          >
            <el-option value="no" :label="$t('NOT_A_Z')" />
            <el-option value="a" :label="$t('TRANS_DIRECT_START')" />
            <el-option value="z" :label="$t('TRANS_DIRECT_END')" />
          </el-select>
        </div>
        <div class="flex mt-10">
          <!-- 全部区域 -->
          <region-cascader
            v-show="stationType == 'no' || stationType == ''"
            style="width: 224px"
            class="mr-10"
            :multiple="true"
            :selected-ids="selectedIds"
            @change="stationChange"
          />
          <!-- A端站点 -->
          <region-cascader
            v-show="stationType === 'a' || stationType === 'z'"
            style="width: 224px"
            class="mr-10"
            :selected-ids="selectedIds"
            :placeholder="stationType === 'a' ? 'A_END_STATION_NAME' : 'Z_END_STATION_NAME'"
            :multiple="true"
            @change="
              val => {
                stationType === 'a' ? aStationChange(val) : zStationChange(val)
              }
            "
          />
          <!-- Z端站点 -->
          <region-cascader
            v-show="stationType === 'a' || stationType === 'z'"
            style="width: 224px"
            :selected-ids="selectedIds"
            :placeholder="stationType === 'a' ? 'Z_END_STATION_NAME' : 'A_END_STATION_NAME'"
            :multiple="true"
            @change="
              val => {
                stationType === 'a' ? zStationChange(val) : aStationChange(val)
              }
            "
          />
        </div>
        <div class="flex justify-end mt-10">
          <el-button type="primary" @click="$debounce(resetOption)">
            {{ $t('RESTORE_DEFAULT_SETTINGS') }}
          </el-button>
          <el-button type="primary" @click="$debounce(search)">
            {{ $t('QUERY') }}
          </el-button>
        </div>
      </div>
    </div>
    <div class="flex-1 pt-10" style="overflow-y: scroll">
      <el-row
        v-for="item in tableData"
        :key="item.id"
        class="link-list p-10"
        :class="item.selected ? 'active' : ''"
        @click.native="debounce(clickEvent, $event, item)"
      >
        <div class="biz-header flex">
          <el-tooltip class="item" effect="dark" :content="item.segmentName" placement="top">
            <p class="biz-name flex-1">{{ item.segmentName || '--' }}</p>
          </el-tooltip>
          <span class="set-threshold" @click="edit(item)">{{ $t('SET_THRESHOLD') }}</span>
        </div>
        <div class="biz-body">
          <p class="biz-name flex align-center">
            {{ $t('LINK_LOSS_THRESHOLD') }}：<span>{{ item.linkLossSill }}</span>
          </p>
          <p class="biz-name flex align-center">
            {{ $t('AVERAGE_LOSS_THRESHOLD') }}：<span>{{ item.avgLossSill }}</span>
          </p>
          <p class="biz-name flex align-center">
            {{ $t('TIP_LENGTH') }}：<span>{{ item.endLengthSill }}</span>
          </p>
          <p class="biz-name flex align-center">
            {{ $t('A_END_STATION') }}：<span>{{
              `${item.startRegionName}/${item.startStationName}`
            }}</span>
          </p>
          <p class="biz-name flex align-center">
            {{ $t('Z_END_STATION') }}：<span>{{
              `${item.endRegionName}/${item.endStationName}`
            }}</span>
          </p>
          <p class="biz-name flex align-center">
            {{ $t('ANODE') }}：<span>{{
              `${item.startNode ? item.startNode.nodeName : item.startNodeId}`
            }}</span>
          </p>
          <p class="biz-name flex align-center">
            {{ $t('ZNODE') }}：<span>{{
              `${item.endNode ? item.endNode.nodeName : item.endNodeId}`
            }}</span>
          </p>
        </div>
      </el-row>
    </div>
    <el-pagination
      v-if="showPage"
      class="mt-10 flex flex-wrap align-center"
      style="white-space: normal; overflow: hidden; height: 65px"
      layout="total, sizes, prev, pager, next, jumper"
      background
      small
      :current-page="pageData.page"
      :page-size="pageData.size"
      :total="pageData.total"
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <edit :visible="thresholdShow" :row-data="rowData" @close="closeEdit" />
  </div>
</template>
<script>
  import { mapGetters, mapMutations } from 'vuex'
  import { getParentsById } from '@/utils/common'
  import logicSegmentApi from '@/api/oen/LogicSegmentApi'
  import RegionCascader from '@/components/RegionCascader'
  import Edit from '@/views/module/conf/alarm/Edit.vue'
  export default {
    components: {
      RegionCascader,
      Edit
    },
    props: {
      showRight: Boolean,
      params: {
        type: Object,
        default() {
          return {
            fiberName: ''
          }
        }
      }
    },
    data() {
      return {
        queryData: {
          filtrationBiz: true, // 可达且不回环的才显示
          keyword: '',
          startStationIdList: [],
          endStationIdList: [],
          stationIdList: []
        },
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        selectedIds: [],
        stationType: '',
        tableData: [],
        thresholdShow: false,
        rowData: {},
        debounceTimer: null,
        showPage: false
      }
    },
    computed: {
      ...mapGetters(['baseRegionList', 'regionTree', 'dictList'])
    },
    watch: {
      params: {
        handler(newVal, oldVal) {
          console.log('link参数变化了', newVal)
          if (newVal.clickProp === 'selectEdge' && this.showRight) {
            this.init()
          }
        }
      },
      showRight: {
        handler(newVal, oldVal) {
          if (!newVal) {
            this.setGisActived({
              cableIds: [],
              nodeIds: [],
              color: ''
            })
          }
        }
      }
    },
    methods: {
      ...mapMutations(['setGisActived']),
      init() {
        if (this.params) {
          this.queryData = { ...this.queryData, ...this.params }
          // this.params.cableId && this.loadData2({ cableId: this.params.cableId }) // 通过点击光缆，获取光缆id，精准查询
          this.loadData()
        }
      },
      loadData() {
        this.showPage = true
        logicSegmentApi
          .queryPage(this.queryData, { page: this.pageData.page, size: this.pageData.size })
          .then(res => {
            this.tableData = res.list || []
            this.tableData.forEach(i => {
              const startRegion = this.getRegionName(i.startStationId)
              const endRegion = this.getRegionName(i.endStationId)
              i.startStationName = startRegion.stationName
              i.startRegionName = startRegion.regionName
              i.endStationName = endRegion.stationName
              i.endRegionName = endRegion.regionName
            })
            this.pageData.total = res.total
            // 之前选中的额链路还在查询列表中，则继续保持高亮
            if (this.rowData.segmentId && this.rowData.selected) {
              const currentRowData = this.tableData.find(
                i => i.segmentId === this.rowData.segmentId
              )
              if (currentRowData) {
                currentRowData.selected = this.rowData.selected
                this.getNodeIdAndCableId(this.rowData)
              } else {
                this.setGisActived({
                  cableIds: [],
                  nodeIds: [],
                  color: ''
                })
                this.rowData = {}
              }
            }
          }).catch(err => {
            console.log(err)
          })
      },
      loadData2(params) {
        this.showPage = false
        logicSegmentApi
          .getListByParam(params)
          .then(res => {
            if (!res) return
            // reach = true(代表可达) ring = true(代表回环) 这里需要过滤出可达且不回环的才在这里显示
            // this.tableData = res.filter(i => i.reach === true && i.ring !== true)
            this.tableData.forEach(i => {
              const startRegion = this.getRegionName(i.startStationId)
              const endRegion = this.getRegionName(i.endStationId)
              i.startStationName = startRegion.stationName
              i.startRegionName = startRegion.regionName
              i.endStationName = endRegion.stationName
              i.endRegionName = endRegion.regionName
            })
            // 之前选中的额链路还在查询列表中，则继续保持高亮
            if (this.rowData.segmentId) {
              const currentRowData = this.tableData.find(
                i => i.segmentId === this.rowData.segmentId
              )
              if (currentRowData) {
                currentRowData.selected = this.rowData.selected
                this.getNodeIdAndCableId(this.rowData)
              } else {
                this.setGisActived({
                  cableIds: [],
                  nodeIds: [],
                  color: ''
                })
                this.rowData = {}
              }
            }
          })
          .catch(() => {})
      },
      // 获取区域/站点/机房
      getRegionName(regionId) {
        const areaList = (getParentsById(this.regionTree, regionId, 'regionId') || []).reverse()
        const obj = {}
        if (areaList.length) {
          obj.stationName = areaList[areaList.length - 1].regionName
          obj.stationId = areaList[areaList.length - 1].regionId
          obj.regionName = areaList
            .slice(0, areaList.length - 1)
            .map(item => item.regionName)
            .join('/')
          obj.regionId = areaList.slice(0, areaList.length - 1).map(item => item.regionId)
        }
        return obj
      },
      // 区域搜索条件改变
      aStationChange(data) {
        this.queryData.startStationIdList = data
      },
      zStationChange(data) {
        this.queryData.endStationIdList = data
      },
      stationChange(data) {
        this.queryData.stationIdList = data
      },
      resetOption() {
        this.selectedIds = []
        this.queryData = this.$options.data().queryData
        this.search()
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        delete this.queryData.cableId
        this.loadData()
      },
      sizeChange(size) {
        this.pageData.size = size
        this.loadData()
      },
      currentChange(page) {
        this.pageData.page = page
        this.loadData()
      },
      edit(row) {
        this.thresholdShow = true
        this.rowData = row
      },
      closeEdit(load) {
        this.thresholdShow = false
        this.rowData = {}
        if (load === true) {
          this.loadData()
        }
      },
      clickEvent(e, data) {
        if (
          e.target.className.includes('set-threshold') ||
          e.target.className.includes('set-threshold')
        ) {
          return
        }
        if (this.rowData.segmentId && this.rowData.segmentId !== data.segmentId) {
          this.tableData.forEach(i => {
            if (i.segmentId === this.rowData.segmentId) {
              i.selected = false
            }
          })
        }
        this.$set(data, 'selected', !data.selected)
        this.rowData = data
        if (this.rowData.selected) {
          this.getNodeIdAndCableId(this.rowData)
        } else {
          this.rowData = {}
          this.setGisActived({
            cableIds: [],
            nodeIds: [],
            color: ''
          })
        }
      },
      getNodeIdAndCableId(rowData) {
        const stations = [rowData.startStationId, rowData.endStationId]
        const cableIds = rowData.networkSegmentList
          .filter(i => {
            return i.cableId
          })
          .map(i => i.cableId)
        console.log(rowData)
        // 判断所选链路段是否有告警信息
        logicSegmentApi
          .getAlarmBySegmentId({ segmentId: rowData.segmentId })
          .then(res => {
            let color = 'color-normal'
            if (res && res.length && res.filter(i => i.isAlarm).length) {
              color = 'color-fault'
            }
            this.setGisActived({
              cableIds: Array.from(new Set(cableIds)),
              nodeIds: Array.from(new Set(stations)),
              color: color
            })
          })
          .catch(() => {})
      },
      reset() {
        Object.assign(this.$data, this.$options.data(this))
      },
      debounce(func, ...args) {
        const context = this
        if (this.debounceTimer) clearTimeout(this.debounceTimer)
        const callNow = !this.debounceTimer // 是否立即执行
        this.debounceTimer = setTimeout(() => {
          this.debounceTimer = null
        }, 500)
        if (callNow) func.apply(context, args)
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';
  .topo-link-segment {
    .search-box {
      overflow: hidden;
      .title {
        @include themeify {
          color: themed('textColor');
        }
        &.active {
          padding-left: 10px;
          height: 30px;
          line-height: 30px;
          @include themeify {
            color: #fff;
            background: themed('topoBizListTitle');
          }
        }
      }
      .search {
        margin: 10px;
        &.active {
        }
      }
      .search-btn {
        line-height: 30px;
        cursor: pointer;
      }
      &.active {
        @include themeify {
          // border: 1px solid themed('homeBorderColor');
          // box-shadow: themed('bigBorderColor') 0px 0px 20px inset;
        }
      }
    }
    .link-list {
      @include themeify {
        color: themed('inputActiveFontColor');
      }
      .biz-header {
        height: 30px;
        .biz-name {
          // white-space: nowrap;
          white-space: pre;
          overflow: hidden;
          text-overflow: ellipsis;
          line-height: 30px;
          @include themeify {
            color: themed('textColor');
          }
          span {
            @include themeify {
              color: themed('textColor');
            }
          }
        }
        .set-threshold {
          @include themeify {
            color: themed('topoFontColor');
          }
        }
      }
      .biz-body {
        .biz-name {
          margin-bottom: 10px;
          span {
            @include themeify {
              color: themed('textColor');
            }
          }
        }
      }
      & + .link-list {
        @include themeify {
          border-top: 1px solid themed('tableBorderColor');
        }
      }
      &:hover {
        @include themeify {
          box-shadow: themed('bigBorderColor') 0px 0px 10px inset;
        }
        cursor: pointer;
      }
      &.active {
        @include themeify {
          box-shadow: themed('bigBorderColor') 0px 0px 20px inset;
        }
      }
    }
  }
</style>
